package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tmh
 * @date 2023/8/19 15:24
 * @description
 */
@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle>
        implements ApArticleService {
    @Resource
    private ApArticleMapper apArticleMapper;

    @Resource
    private ApArticleConfigMapper apArticleConfigMapper;

    @Resource
    private ApArticleContentMapper apArticleContentMapper;

    @Resource
    private ArticleFreemarkerService articleFreemarkerService;

    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        //1.校验参数
        //分页条数的校验
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            dto.setSize(10);
        }
        //分页的值不超过50
        dto.setSize(Math.min(size, MAX_PAGE_SIZE));
        //校验参数 --type
        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) || type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //频道参数校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间校验
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(apArticleList);
    }

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {

        //测试feign的降级
//        try {
//            Thread.sleep(3000);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//ArticleDto(content=[{"type":"text","value":"测试保存文章"},{"type":"text","value":"请在这里输入正文"}])
        log.info("saveArticle:{}", dto);

        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //2.是否存在id
        if (dto.getId() == null) {
            //2.1不存在id 保存 文章  文章配置 文章内容
            save(apArticle);
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            //保存配置
            apArticleConfigMapper.insert(apArticleConfig);
            //保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        } else {
            //在原来发布过的文章的基础之上修改文章内容，此时的articleId就还是之前的，所以传入的
            //dto.getId也还是第一次生成的id
            //2.2存在id 修改 文章 文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                    Wrappers.<ApArticleContent>lambdaQuery().
                            eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        //结果返回 文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if (firstPage) {
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonStr)) {
                //这里和视频里面的代码有差距，根据自己的理解来写的
                //如果没有数据，那么json字符串就是一个[]，也是不为空的，所以这里我们用判断集合是否为空来决定是否加载热点数据或者其他数据
                //不然返回给前端的就是一个空数组，使得前端就会展示不出数据来
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                if (!hotArticleVoList.isEmpty()) {
                    return ResponseResult.okResult(hotArticleVoList);
                } else {
                    return load(dto, type);
                }
            }
        }
        return load(dto, type);
    }


    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读，点赞，收藏，评论的数量
        ApArticle apArticle = updateArticle(mess);

        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;

        //3.替换当前文章对频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * @param apArticle
     * @param score
     * @param s
     */
    public void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        //从redis里面查询热点文章
        String articleListStr = cacheService.get(s);
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);
        if (!hotArticleVoList.isEmpty()) {
            //flag用来判断这个数据在缓存里面存不存在 true:表示在缓存中不存在 false：表示在缓存中存在
            boolean flag = true;
            //如果缓存中存在该文章，那么只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据,就替换
            if (flag) {
                //判断缓存中的热点数据是否大于等于三十条(其实缓存里面的数据最多就只有三十条)
                if (hotArticleVoList.size() >= 30) {
                    //将集合进行排序
                    hotArticleVoList = hotArticleVoList.stream()
                            .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                            .collect(Collectors.toList());
                    //得到最后一条
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    //判断最后一条数据与当前数据的分值
                    if (lastHot.getScore() < score) {
                        //移除最后一条数据
                        hotArticleVoList.remove(lastHot);
                        //把当前的数据添加进来
                        HotArticleVo hot = new HotArticleVo();
                        //属性拷贝
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }
                } else {
                    //缓存中的数据小于三十条，我们直接把这条数据添加进来
                    HotArticleVo hot = new HotArticleVo();
                    //属性拷贝
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
        } else {
            //如果该集合里面没有热点数据即为0条，也是直接把当前数据添加进来
            HotArticleVo hot = new HotArticleVo();
            //属性拷贝
            BeanUtils.copyProperties(apArticle, hot);
            hot.setScore(score);
            hotArticleVoList.add(hot);
        }
        //缓存到redis里面
        hotArticleVoList = hotArticleVoList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .collect(Collectors.toList());
        cacheService.set(s, JSON.toJSONString(hotArticleVoList));

    }

    /**
     * 更新文章的阅读，点赞，收藏，评论的数量
     *
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        System.out.println("传入的mess.getView是" + mess.getView());
        if (apArticle.getComment() == null) {
            apArticle.setComment(0);
        }
        if (apArticle.getViews() == null) {
            apArticle.setViews(0);
        }
        if (apArticle.getCollection() == null) {
            apArticle.setCollection(0);
        }
        if (apArticle.getLikes() == null) {
            apArticle.setLikes(0);
        }

        apArticle.setCollection(apArticle.getCollection() + mess.getCollect());
        apArticle.setComment(apArticle.getComment() + mess.getComment());
        apArticle.setLikes(apArticle.getLikes() + mess.getLike());
        apArticle.setViews(apArticle.getViews() + mess.getView());

        System.out.println("阅读操作之后的Views是" + apArticle.getViews());

        updateById(apArticle);
        log.info("updateArticle:{}" + apArticle);
        return apArticle;
    }

    /**
     * 计算文章的具体分值
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }


}
